package com.system.api;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.system.entity.po.DocumentDo;
import com.system.mapper.DocumentMapper;
import com.system.utils.R;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/api")
@RestController
public class CheckFileController {

    @Autowired
    private DocumentMapper documentMapper;

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        StringBuilder contentBuilder = new StringBuilder();
        try (InputStream fis = file.getInputStream(); XWPFDocument document = new XWPFDocument(fis)) {
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                contentBuilder.append(paragraph.getText());
                contentBuilder.append("\n");
            }
        }
        String content = contentBuilder.toString();
        System.out.println(content);


        DocumentDo documentDo = new DocumentDo();
        documentDo.setId(IdUtil.getSnowflakeNextId());
        documentDo.setType(file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf('.')));
        documentDo.setContent(content);

        documentMapper.insert(documentDo);

        return R.SUCCESS("上传成功!");
    }


    @PostMapping("/check")
    public R check() throws Exception{
        List<DocumentDo> documentDoList = documentMapper.selectList();

        DocumentDo documentDo1 = documentDoList.stream().filter(d -> "起诉书".equals(d.getType())).findFirst().get();
        DocumentDo documentDo2 = documentDoList.stream().filter(d -> "立案通知书".equals(d.getType())).findFirst().get();
        DocumentDo documentDo3 = documentDoList.stream().filter(d -> "一审判决书".equals(d.getType())).findFirst().get();
        DocumentDo documentDo4 = documentDoList.stream().filter(d -> "上诉状".equals(d.getType())).findFirst().get();
        DocumentDo documentDo5 = documentDoList.stream().filter(d -> "二审判决书".equals(d.getType())).findFirst().get();
        DocumentDo documentDo6 = documentDoList.stream().filter(d -> "执行申请书".equals(d.getType())).findFirst().get();
        DocumentDo documentDo7 = documentDoList.stream().filter(d -> "执行裁定书".equals(d.getType())).findFirst().get();
        DocumentDo documentDo8 = documentDoList.stream().filter(d -> "结案通知书".equals(d.getType())).findFirst().get();

        // 构建提示词
        String prompt = String.format(
                "请帮我验证以下法律文书之间的内容关联性，检查是否存在不一致或矛盾的地方：" +
                        " 1. 起诉书内容："
                        + "%s"
                        + ""
                        + "2. 立案通知书内容："
                        + "%s"
                        + ""
                        + "3. 一审判决书内容："
                        + "%s"
                        + ""
                        + "4. 上诉状内容："
                        + "%s"
                        + ""
                        + "5. 二审判决书内容："
                        + "%s"
                        + ""
                        + "6. 执行申请书内容："
                        + "%s"
                        + ""
                        + "7. 执行裁定书内容："
                        + "%s"
                        + ""
                        + "8. 结案通知书内容："
                        + "%s"
                        + ""
                        + "请详细分析这些文书之间的关联性"
                        + ""
                        + "如果发现任何不一致或矛盾的地方，请明确指出具体是哪个文书中的哪部分内容存在问题。",
                documentDo1.getContent(),
                documentDo2.getContent(),
                documentDo3.getContent(),
                documentDo4.getContent(),
                documentDo5.getContent(),
                documentDo6.getContent(),
                documentDo7.getContent(),
                documentDo8.getContent()
        );


        // 创建请求体的JSON对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("prompt", prompt);
        requestBodyMap.put("max_tokens", 150); // 根据需要调整
        String requestBodyJson = objectMapper.writeValueAsString(requestBodyMap);


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model","deepseek-chat");
        List<Map<String ,Object>> messagesList = new ArrayList<>();
        Map<String ,Object> userMap = new HashMap<>();
        userMap.put("role","user");
        userMap.put("content",prompt);
        messagesList.add(userMap);
        jsonObject.put("messages",messagesList);
        jsonObject.put("temperature",0.7);
        jsonObject.put("stream",false);



        // 调用DeepSeek API
        String apiKey = "sk-27d003c764a7444d85b984f4e297f5fb"; // 需要替换为实际的API密钥
        String apiUrl = "https://api.deepseek.com/v1/chat/completions";



        // 发送HTTP请求
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(apiUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(jsonObject.toString()))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 解析响应
            if (response.statusCode() == 200) {
                // 处理API返回的结果
                String result = response.body();

                JSONObject resultObject = JSONObject.parseObject(result);
                JSONArray choices = resultObject.getJSONArray("choices");
                JSONObject choiceObject = choices.getJSONObject(0);
                JSONObject messageObject = choiceObject.getJSONObject("message");
                String content = messageObject.getString("content");

                return R.SUCCESS("操作超过",content);
            } else {
                return R.FAILED("API调用失败，状态码：" + response.statusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.FAILED("API调用异常：" + e.getMessage());
        }
    }

}
